package com.example.goodscontentresolver;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

import android.Manifest;
import android.content.ContentProviderOperation;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.Settings;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ContentInfoCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.goodscontentresolver.utils.MessageObserver;
import com.example.goodscontentresolver.utils.PermissionUtil;

import android.provider.ContactsContract;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements View.OnLongClickListener {

    public static final String GOODS_CONTENT_PROVIDER_PREFIX = "content://com.example.cart.providers.GoodsContentProvider/goods";
    private Uri goodsApp;
    private LinearLayout goodsList;

    /*
     * 联系人读写权限
     * */
    private String[] ContactsPermissions = new String[]{
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.WRITE_CONTACTS
    };

    /*读写短信的权限*/
    private String[] MessagesPermissions = new String[]{
            Manifest.permission.SEND_SMS,
            Manifest.permission.READ_SMS
    };

    private final int ContactsRequestCode = 1;
    private final int MessageRequestCode = 2;
    private MessageObserver messageObserver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });


        goodsApp = Uri.parse(GOODS_CONTENT_PROVIDER_PREFIX);

        goodsList = findViewById(R.id.goodsList);

        findViewById(R.id.queryGoods).setOnClickListener(view -> {

            loadCart();
        });


        findViewById(R.id.clearCart).setOnClickListener(view -> {
            getContentResolver().delete(goodsApp, null, null);
            loadCart();
        });

        /**
         * 动态权限需要先声明 AndroidManifest.xml 中声明
         */
        findViewById(R.id.contacts).setOnClickListener(view -> {
            if (PermissionUtil.requestPermission(this, ContactsRequestCode, ContactsPermissions)) {
                // 有权限执行添加联系人
                addContactWithTransaction("罗俊华", "13211634008", "1007052116@qq.com");

            }

        });

        findViewById(R.id.queryContacts).setOnClickListener(view -> {
            if (PermissionUtil.requestPermission(this, ContactsRequestCode, ContactsPermissions)) {
                // 有权限执行查询联系人
                loadContacts();
            }
        });

        findViewById(R.id.messages).setOnClickListener(view -> {
            PermissionUtil.requestPermission(this, MessageRequestCode, MessagesPermissions);

        });

//      注册短信监听器，在 Activity 终止的时候记得取消注册
        messageObserver = new MessageObserver(getContentResolver());
        getContentResolver().registerContentObserver(Uri.parse("content://sms"),true, messageObserver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消注册短信监听器
        getContentResolver().unregisterContentObserver(messageObserver);
    }

    private void loadContacts() {

        try (Cursor cursor = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, new String[]{ContactsContract.Contacts._ID}, null, null, null)) {
            if (cursor == null) {

                return;
            }

            while (cursor.moveToNext()) {
                String rawContactId = cursor.getString(0);

                try (Cursor item = getContentResolver().query(Uri.parse("content://com.android.contacts/contacts/" + rawContactId + "/data"), new String[]{
                        ContactsContract.Data.DATA1, ContactsContract.Data.DATA2, ContactsContract.Data.MIMETYPE
                }, null, null, null)) {
                    if (item == null) {
                        continue;
                    }
                    StringBuilder text = new StringBuilder();
                    while (item.moveToNext()) {
                        switch (item.getString(2)) {
                            case ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE:
                            case ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE:
                            case ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE: {
                                text.append(item.getString(0));
                                break;
                            }
                        }
                        text.append("            ");
                    }
                    TextView textView = new TextView(this);

                    textView.setText(text.toString());
                    goodsList.addView(textView);
                }
            }
        }
    }

    /**
     * 缺点：不能保障事务
     *
     * @param name
     * @param phone
     * @param email
     */
    private void addContact(String name, String phone, String email) {

        ContentValues values = new ContentValues();
        // 插入联系人主表
        Uri insert = getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, values);
        if (insert == null) {
            Toast.makeText(this, "插入联系人主表失败", Toast.LENGTH_SHORT).show();
            return;
        }
        long contactId = ContentUris.parseId(insert);

        // 插入联系人姓名
        ContentValues nameValue = new ContentValues();
        // 关联联系人主表
        nameValue.put(ContactsContract.Data.RAW_CONTACT_ID, contactId);
        // 类型
        nameValue.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
        nameValue.put(ContactsContract.Data.DATA2, name);
        getContentResolver().insert(ContactsContract.Data.CONTENT_URI, nameValue);

        // 插入联系人电话
        ContentValues phoneValue = new ContentValues();
        // 关联联系人主表
        phoneValue.put(ContactsContract.Data.RAW_CONTACT_ID, contactId);
        // 类型:电话
        phoneValue.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
        phoneValue.put(ContactsContract.Data.DATA1, phone);
        phoneValue.put(ContactsContract.Data.DATA2, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
        getContentResolver().insert(ContactsContract.Data.CONTENT_URI, phoneValue);

        // 插入联系人邮箱
        ContentValues emailValue = new ContentValues();
        // 关联联系人主表
        emailValue.put(ContactsContract.Data.RAW_CONTACT_ID, contactId);
        // 类型
        emailValue.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
        emailValue.put(ContactsContract.Data.DATA1, email);
        phoneValue.put(ContactsContract.Data.DATA2, ContactsContract.CommonDataKinds.Email.TYPE_WORK);

        getContentResolver().insert(ContactsContract.Data.CONTENT_URI, emailValue);

        Toast.makeText(this, "插入成功", Toast.LENGTH_SHORT).show();
    }

    private void addContactWithTransaction(String name, String phone, String email) {
        ContentProviderOperation id = ContentProviderOperation
                .newInsert(ContactsContract.RawContacts.CONTENT_URI)
                .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
                .build();

        ContentProviderOperation nameData = ContentProviderOperation
                .newInsert(ContactsContract.Data.CONTENT_URI)
                // 使用第0个操作的id，即 raw_contacts 的 id 作为 data 表中的 raw_contact_id
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.Data.DATA2, name)
                .build();

        ContentProviderOperation phoneData = ContentProviderOperation
                .newInsert(ContactsContract.Data.CONTENT_URI)
                // 使用第0个操作的id，即 raw_contacts 的 id 作为 data 表中的 raw_contact_id
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.Data.DATA1, phone)
                .withValue(ContactsContract.Data.DATA2, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
                .build();

        ContentProviderOperation emailData = ContentProviderOperation
                .newInsert(ContactsContract.Data.CONTENT_URI)
                // 使用第0个操作的id，即 raw_contacts 的 id 作为 data 表中的 raw_contact_id
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.Data.DATA1, email)
                .withValue(ContactsContract.Data.DATA2, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
                .build();

        try {
            getContentResolver().applyBatch(ContactsContract.AUTHORITY, new ArrayList<>(Arrays.asList(id, nameData, phoneData, emailData)));
        } catch (OperationApplicationException | RemoteException e) {
            Toast.makeText(this, "添加失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(this, name + "添加成功", Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean grantSuccess = false;
        for (int i = 0; i < permissions.length; i++) {
            String permission = permissions[i];
            grantSuccess = PERMISSION_GRANTED == grantResults[i];
            if (!grantSuccess) {
                break;
            }
        }

        String text = "";
        switch (requestCode) {
            case ContactsRequestCode: {
                // 联系人授权结果
                text = "联系人授权结果";
                break;
            }
            case MessageRequestCode: {
                // 短信授权结果
                text = "短信授权结果";
                break;
            }
        }

        Toast.makeText(this, text + (grantSuccess ? "成功" : "失败"), Toast.LENGTH_SHORT).show();


        if (!grantSuccess) {
            // 授权失败，跳转应用详情页，请求权限
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.fromParts("package", getPackageName(), null));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }

    private void loadCart() {

        goodsList.removeAllViews();

        try (Cursor cursor = getContentResolver().query(goodsApp, null, null, null, null)) {
            if (cursor == null) {
                Toast.makeText(this, "未找到ContentProvider", Toast.LENGTH_SHORT).show();
                return;
            }

            while (cursor.moveToNext()) {
                TextView goodsName = new TextView(this);

                // 商品名称
                goodsName.setText(cursor.getString(0));
                goodsName.setOnLongClickListener(this);

                // 购物车id
                goodsName.setTag(cursor.getInt(1));
                goodsList.addView(goodsName, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 50));

            }


        }
    }

    @Override
    public boolean onLongClick(View v) {

        int cartId = (int) v.getTag();

        new AlertDialog.Builder(this)
                .setTitle("确认删除" + ((TextView) v).getText() + "吗?")
                .setPositiveButton("删除", (dialog, which) -> {
                    // 更快捷的拼接Uri方式 Uri.parse(GOODS_CONTENT_PROVIDER_PREFIX + "/" + cartId);

                    Uri uri = ContentUris.withAppendedId(goodsApp, cartId);
                    getContentResolver().delete(uri, null, null);
                    loadCart();
                }).setNegativeButton("取消", null)
                .create().show();

        return true;
    }
}